package com.learn.xueer.ui.viewmodel

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.learn.xueer.app.appViewModel
import com.learn.xueer.app.network.ApiService
import com.learn.xueer.app.network.apiService
import com.learn.xueer.app.util.CacheUtil
import com.learn.xueer.data.model.bean.HearSayResponse
import com.learn.xueer.data.model.bean.MissionHistoryResponse
import com.learn.xueer.data.model.bean.QuestionResponse
import com.learn.xueer.data.model.bean.SectionBean
import com.learn.xueer.data.model.bean.SettingResponse
import com.learn.xueer.data.model.bean.StudyHistoryResponse
import com.learn.xueer.data.model.bean.UploadResponse
import com.learn.xueer.data.model.bean.UserInfoResponse
import com.learn.xueer.data.model.bean.VipDetailResponse
import com.learn.xueer.data.model.bean.VipResponse
import com.learn.xueer.ui.activity.LoginActivity
import me.hgj.jetpackmvvm.base.appContext
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.util.ActivityMessenger
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import java.io.File

class MineViewModel : BaseViewModel() {
    var hearSayResult = MutableLiveData<MutableList<HearSayResponse>?>()
    var userInfo = MutableLiveData<UserInfoResponse>()
    var settingInfo = MutableLiveData<SettingResponse>()
    var vip = MutableLiveData<VipResponse>()
    var vipDetail = MutableLiveData<VipDetailResponse>()
    var feedContent = MutableLiveData<String>()
    var missionHistoryResponse = MutableLiveData<MissionHistoryResponse>()
    var feedResult = MutableLiveData<Boolean>().apply { postValue(false) }

    fun settingReq() {
        request({ apiService.getSetting() }, {
            //请求成功 已自动处理了 请求结果是否正常
            settingInfo.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
        }, true)

    }

    fun aboutReq() {
        request({ apiService.getAbout() }, {
            //请求成功 已自动处理了 请求结果是否正常
            appViewModel.about.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
        }, true)

    }

    fun missionHistoryReq(month: String) {
        request({ apiService.missionHistory(month) }, {
            //请求成功 已自动处理了 请求结果是否正常
            missionHistoryResponse.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里

        }, true)

    }

    fun studyHistory(back: (data: MutableList<SectionBean>?) -> Unit, fail: () -> Unit) {
        val retrofit = Retrofit.Builder()
            .baseUrl(ApiService.SERVER_URL)
            .build()
        val service: ApiService = retrofit.create(ApiService::class.java)
        val call: Call<ResponseBody> = service.studyHistory(CacheUtil.getToken())
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.code() == 200) {
                    try {
                        var jsonObject = response.body()?.string()?.let { JSONObject(it) }
                        var code = jsonObject?.getInt("code")
                        var msg = jsonObject?.getString("msg")
                        var data = jsonObject?.getJSONObject("data")
                        if (code == 1) {
                            var arrayList = ArrayList<SectionBean>()

                            data?.keys()?.forEach {
                                var get = data.getJSONArray(it).toString()
                                val history = Gson().fromJson<ArrayList<StudyHistoryResponse>>(
                                    get,
                                    object : TypeToken<ArrayList<StudyHistoryResponse>>() {}.type
                                )
                                arrayList.add(SectionBean(it, history))
                            }
                            back(arrayList)
                        } else {
                            fail()
                            ToastUtils.showShort(msg)
                        }


                    } catch (e: Exception) {
                        fail()
                        LogUtils.e("error:${e.message}")
                    }


                } else {
                    fail()
                    if (response.code() == 401) {
                        me.hgj.jetpackmvvm.util.LogUtils.debugInfo("1111111")
                        CacheUtil.clearAll()
                        ActivityMessenger.startActivityNew(appContext, LoginActivity::class)
                        KtxActivityManger.finishAllActivity()
                    }
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                fail()
                ToastUtils.showShort(t.message)

            }

        })


    }

    fun feedBackReq() {
        request({ apiService.feedBack(feedContent.value ?: "") }, {
            //请求成功 已自动处理了 请求结果是否正常
            feedResult.value = true
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里

        }, true)

    }

    fun eyeReq(eye: String, call: (Boolean) -> Unit) {
        request({ apiService.updateEye(eye) }, {
            //请求成功 已自动处理了 请求结果是否正常
            userInfo.value?.is_eyeshield = eye
            settingInfo.value?.is_eyeshield = eye != "1"
            call(true)
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
            call(false)
        }, true)

    }

    fun problemReq(back: (data: MutableList<QuestionResponse>?) -> Unit) {
        request({ apiService.problem() }, {
            back(it)
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }

    fun vipReq() {
        request({ apiService.getVip() }, {
            vip.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }

    fun getVipInfo(id: String) {
        request({ apiService.getVipInfo(id) }, {
            if (it?.info?.grade_type == "1") {
                it.info.grade_name = "小学"
            } else if (it?.info?.grade_type == "2") {
                it.info.grade_name = "初中"
            } else if (it?.info?.grade_type == "3") {
                it.info.grade_name = "高中"
            }
            vipDetail.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }

    fun orderListReq() {
        request({ apiService.getOrderList() }, {
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)

    }

    fun bookSectionReq(grade: String) {
        var params = HashMap<String, Any>()
        params["grade"] = grade
        request({
            val requestBody = RequestBody.create(
                MediaType.get("multipart/form-data"),
                Gson().toJson(params)
            )
            apiService.getHearSay(requestBody)
        }, {
            hearSayResult.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)
    }

    fun createOrder() {
        request({
            apiService.createOrder()
        }, {

        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)
    }

    fun uploadAvatarReq(file: File, back: (url: String) -> Unit) {

        LogUtils.e(file.path)

        val requestBody = RequestBody.create(
            MediaType.get("multipart/form-data"),
            file
        )
        var createFormData = MultipartBody.Part.createFormData("file", file.name, requestBody)

        val retrofit = Retrofit.Builder()
            .baseUrl(ApiService.SERVER_URL)
            .build()

        val service: ApiService = retrofit.create(ApiService::class.java)
        val call: Call<ResponseBody> = service.uploadFile(createFormData, CacheUtil.getToken())
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                if (response.code() == 200) {
                    try {
                        var fromJson = Gson().fromJson<UploadResponse>(
                            response.body()?.string(),
                            UploadResponse::class.java
                        )
                        LogUtils.e("fromJson:$fromJson")
                        if (fromJson.code == 1) {
                            back(fromJson.data.fullurl)
                        } else {
                            ToastUtils.showShort(fromJson.msg + "")
                        }
                    } catch (e: Exception) {
                        LogUtils.e("error:${e.message}")
                    }


                } else {
                    if (response.code() == 401) {
                        me.hgj.jetpackmvvm.util.LogUtils.debugInfo("1111111")
                        CacheUtil.clearAll()
                        ActivityMessenger.startActivityNew(appContext, LoginActivity::class)
                        KtxActivityManger.finishAllActivity()
                    }
                }
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                ToastUtils.showShort(t.message + "")

            }

        })

    }

    fun userInfoReq() {
        request({ apiService.getUserInfo() }, {
            userInfo.value = it
        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)
    }

    fun updateProfile(url: String,success:()->Unit) {
        request({ apiService.updateProfile(url) }, {
            success()
            ToastUtils.showShort("头像上传成功")

        }, {
            //请求失败 网络异常，或者请求结果码错误都会回调在这里
            ToastUtils.showShort(it.errorMsg)
        }, true)
    }

}